<?php

// +----------------------------------------------------------------------
// | OneThink [ WE CAN DO IT JUST THINK IT ]
// +----------------------------------------------------------------------
// | Copyright (c) 2013 http://www.onethink.cn All rights reserved.
// +----------------------------------------------------------------------
// | Author: 麦当苗儿 <zuojiazi@vip.qq.com> <http://www.zjzit.cn>
// +----------------------------------------------------------------------

/**
 * 后台公共文件
 * 主要定义后台公共函数库
 */
/* 解析列表定义规则 */

function get_list_field($data, $grid) {

    // 获取当前字段数据
    foreach ($grid['field'] as $field) {
        $array = explode('|', $field);
        $temp = $data[$array[0]];
        // 函数支持
        if (isset($array[1])) {
            $temp = call_user_func($array[1], $temp);
        }
        $data2[$array[0]] = $temp;
    }
    if (!empty($grid['format'])) {
        $value = preg_replace_callback('/\[([a-z_]+)\]/', function($match) use($data2) {
            return $data2[$match[1]];
        }, $grid['format']);
    } else {
        $value = implode(' ', $data2);
    }

    // 链接支持
    if ('title' == $grid['field'][0] && '目录' == $data['type']) {
        // 目录类型自动设置子文档列表链接
        $grid['href'] = '[LIST]';
    }
    if (!empty($grid['href'])) {
        $links = explode(',', $grid['href']);
        foreach ($links as $link) {
            $array = explode('|', $link);
            $href = $array[0];
            if (preg_match('/^\[([a-z_]+)\]$/', $href, $matches)) {
                $val[] = $data2[$matches[1]];
            } else {
                $show = isset($array[1]) ? $array[1] : $value;
                // 替换系统特殊字符串
                $href = str_replace(
                        array('[DELETE]', '[EDIT]', '[LIST]'), array('setstatus?status=-1&ids=[id]',
                    'edit?id=[id]&model=[model_id]&cate_id=[category_id]',
                    'index?pid=[id]&model=[model_id]&cate_id=[category_id]'), $href);

                // 替换数据变量
                $href = preg_replace_callback('/\[([a-z_]+)\]/', function($match) use($data) {
                    return $data[$match[1]];
                }, $href);

                $val[] = '<a href="' . U($href) . '">' . $show . '</a>';
            }
        }
        $value = implode(' ', $val);
    }
    return $value;
}

/* 解析插件数据列表定义规则 */

function get_addonlist_field($data, $grid, $addon) {
    // 获取当前字段数据
    foreach ($grid['field'] as $field) {
        $array = explode('|', $field);
        $temp = $data[$array[0]];
        // 函数支持
        if (isset($array[1])) {
            $temp = call_user_func($array[1], $temp);
        }
        $data2[$array[0]] = $temp;
    }
    if (!empty($grid['format'])) {
        $value = preg_replace_callback('/\[([a-z_]+)\]/', function($match) use($data2) {
            return $data2[$match[1]];
        }, $grid['format']);
    } else {
        $value = implode(' ', $data2);
    }

    // 链接支持
    if (!empty($grid['href'])) {
        $links = explode(',', $grid['href']);
        foreach ($links as $link) {
            $array = explode('|', $link);
            $href = $array[0];
            if (preg_match('/^\[([a-z_]+)\]$/', $href, $matches)) {
                $val[] = $data2[$matches[1]];
            } else {
                $show = isset($array[1]) ? $array[1] : $value;
                // 替换系统特殊字符串
                $href = str_replace(
                        array('[DELETE]', '[EDIT]', '[ADDON]'), array('del?ids=[id]&name=[ADDON]', 'edit?id=[id]&name=[ADDON]', $addon), $href);

                // 替换数据变量
                $href = preg_replace_callback('/\[([a-z_]+)\]/', function($match) use($data) {
                    return $data[$match[1]];
                }, $href);

                $val[] = '<a href="' . U($href) . '">' . $show . '</a>';
            }
        }
        $value = implode(' ', $val);
    }
    return $value;
}

// 获取模型名称
function get_model_by_id($id) {
    return $model = M('Model')->getFieldById($id, 'title');
}

// 获取属性类型信息
function get_attribute_type($type = '') {
    // TODO 可以加入系统配置
    static $_type = array(
        'num' => array('数字', 'int(10) UNSIGNED NOT NULL'),
        'string' => array('字符串', 'varchar(255) NOT NULL'),
        'textarea' => array('文本框', 'text NOT NULL'),
        'date' => array('日期', 'int(10) NOT NULL'),
        'datetime' => array('时间', 'int(10) NOT NULL'),
        'bool' => array('布尔', 'tinyint(2) NOT NULL'),
        'select' => array('枚举', 'char(50) NOT NULL'),
        'radio' => array('单选', 'char(10) NOT NULL'),
        'checkbox' => array('多选', 'varchar(100) NOT NULL'),
        'editor' => array('编辑器', 'text NOT NULL'),
        'picture' => array('上传图片', 'int(10) UNSIGNED NOT NULL'),
        'file' => array('上传附件', 'int(10) UNSIGNED NOT NULL'),
    );
    return $type ? $_type[$type][0] : $_type;
}

/**
 * 获取对应状态的文字信息
 * @param int $status
 * @return string 状态文字 ，false 未获取到
 * @author huajie <banhuajie@163.com>
 */
function get_status_title($status = null) {
    if (!isset($status)) {
        return false;
    }
    switch ($status) {
        case -1 : return '已删除';
            break;
        case 0 : return '禁用';
            break;
        case 1 : return '正常';
            break;
        case 2 : return '待审核';
            break;
        default : return false;
            break;
    }
}

// 获取数据的状态操作
function show_status_op($status) {
    switch ($status) {
        case 0 : return '启用';
            break;
        case 1 : return '禁用';
            break;
        case 2 : return '审核';
            break;
        default : return false;
            break;
    }
}

/**
 * 获取文档的类型文字
 * @param string $type
 * @return string 状态文字 ，false 未获取到
 * @author huajie <banhuajie@163.com>
 */
function get_document_type($type = null) {
    if (!isset($type)) {
        return false;
    }
    switch ($type) {
        case 1 : return '目录';
            break;
        case 2 : return '主题';
            break;
        case 3 : return '段落';
            break;
        default : return false;
            break;
    }
}

/**
 * 获取配置的类型
 * @param string $type 配置类型
 * @return string
 */
function get_config_type($type = 0) {
    $list = C('CONFIG_TYPE_LIST');
    return $list[$type];
}

/**
 * 获取配置的分组
 * @param string $group 配置分组
 * @return string
 */
function get_config_group($group = 0) {
    $list = C('CONFIG_GROUP_LIST');
    return $group ? $list[$group] : '';
}

/**
 * select返回的数组进行整数映射转换
 *
 * @param array $map  映射关系二维数组  array(
 *                                          '字段名1'=>array(映射关系数组),
 *                                          '字段名2'=>array(映射关系数组),
 *                                           ......
 *                                       )
 * @author 朱亚杰 <zhuyajie@topthink.net>
 * @return array
 *
 *  array(
 *      array('id'=>1,'title'=>'标题','status'=>'1','status_text'=>'正常')
 *      ....
 *  )
 *
 */
function int_to_string(&$data, $map = array('status' => array(1 => '正常', -1 => '删除', 0 => '禁用', 2 => '未审核', 3 => '草稿'))) {
    if ($data === false || $data === null) {
        return $data;
    }
    $data = (array) $data;
    foreach ($data as $key => $row) {
        foreach ($map as $col => $pair) {
            if (isset($row[$col]) && isset($pair[$row[$col]])) {
                $data[$key][$col . '_text'] = $pair[$row[$col]];
            }
        }
    }
    return $data;
}

/**
 * 动态扩展左侧菜单,base.html里用到
 * @author 朱亚杰 <zhuyajie@topthink.net>
 */
function extra_menu($extra_menu, &$base_menu) {
    foreach ($extra_menu as $key => $group) {
        if (isset($base_menu['child'][$key])) {
            $base_menu['child'][$key] = array_merge($base_menu['child'][$key], $group);
        } else {
            $base_menu['child'][$key] = $group;
        }
    }
}

/**
 * 获取参数的所有父级分类
 * @param int $cid 分类id
 * @return array 参数分类和父类的信息集合
 * @author huajie <banhuajie@163.com>
 */
function get_parent_category($cid) {
    if (empty($cid)) {
        return false;
    }
    $cates = M('Category')->where(array('status' => 1))->field('id,title,pid')->order('sort')->select();
    $child = get_category($cid); //获取参数分类的信息
    $pid = $child['pid'];
    $temp = array();
    $res[] = $child;
    while (true) {
        foreach ($cates as $key => $cate) {
            if ($cate['id'] == $pid) {
                $pid = $cate['pid'];
                array_unshift($res, $cate); //将父分类插入到数组第一个元素前
            }
        }
        if ($pid == 0) {
            break;
        }
    }
    return $res;
}

/**
 * 检测验证码
 * @param  integer $id 验证码ID
 * @return boolean     检测结果
 * @author 麦当苗儿 <zuojiazi@vip.qq.com>
 */
function check_verify($code, $id = 1) {
    $verify = new \Think\Verify();
    return $verify->check($code, $id);
}

/**
 * 获取当前分类的文档类型
 * @param int $id
 * @return array 文档类型数组
 * @author huajie <banhuajie@163.com>
 */
function get_type_bycate($id = null) {
    if (empty($id)) {
        return false;
    }
    $type_list = C('DOCUMENT_MODEL_TYPE');
    $model_type = M('Category')->getFieldById($id, 'type');
    $model_type = explode(',', $model_type);
    foreach ($type_list as $key => $value) {
        if (!in_array($key, $model_type)) {
            unset($type_list[$key]);
        }
    }
    return $type_list;
}

/**
 * 获取当前文档的分类
 * @param int $id
 * @return array 文档类型数组
 * @author huajie <banhuajie@163.com>
 */
function get_cate($cate_id = null) {
    if (empty($cate_id)) {
        return false;
    }
    $cate = M('Category')->where('id=' . $cate_id)->getField('title');
    return $cate;
}

// 分析枚举类型配置值 格式 a:名称1,b:名称2
function parse_config_attr($string) {
    $array = preg_split('/[,;\r\n]+/', trim($string, ",;\r\n"));
    if (strpos($string, ':')) {
        $value = array();
        foreach ($array as $val) {
            list($k, $v) = explode(':', $val);
            $value[$k] = $v;
        }
    } else {
        $value = $array;
    }
    return $value;
}

// 获取子文档数目
function get_subdocument_count($id = 0) {
    return M('Document')->where('pid=' . $id)->count();
}

// 分析枚举类型字段值 格式 a:名称1,b:名称2
// 暂时和 parse_config_attr功能相同
// 但请不要互相使用，后期会调整
function parse_field_attr($string) {
    if (0 === strpos($string, ':')) {
        // 采用函数定义
        return eval('return ' . substr($string, 1) . ';');
    } elseif (0 === strpos($string, '[')) {
        // 支持读取配置参数（必须是数组类型）
        return C(substr($string, 1, -1));
    }

    $array = preg_split('/[,;\r\n]+/', trim($string, ",;\r\n"));
    if (strpos($string, ':')) {
        $value = array();
        foreach ($array as $val) {
            list($k, $v) = explode(':', $val);
            $value[$k] = $v;
        }
    } else {
        $value = $array;
    }
    return $value;
}

/**
 * 获取行为数据
 * @param string $id 行为id
 * @param string $field 需要获取的字段
 * @author huajie <banhuajie@163.com>
 */
function get_action($id = null, $field = null) {
    if (empty($id) && !is_numeric($id)) {
        return false;
    }
    $list = S('action_list');
    if (empty($list[$id])) {
        $map = array('status' => array('gt', -1), 'id' => $id);
        $list[$id] = M('Action')->where($map)->field(true)->find();
    }
    return empty($field) ? $list[$id] : $list[$id][$field];
}

/**
 * 根据条件字段获取数据
 * @param mixed $value 条件，可用常量或者数组
 * @param string $condition 条件字段
 * @param string $field 需要返回的字段，不传则返回整个数据
 * @author huajie <banhuajie@163.com>
 */
function get_document_field($value = null, $condition = 'id', $field = null) {
    if (empty($value)) {
        return false;
    }

    //拼接参数
    $map[$condition] = $value;
    $info = M('Model')->where($map);
    if (empty($field)) {
        $info = $info->field(true)->find();
    } else {
        $info = $info->getField($field);
    }
    return $info;
}

/**
 * 获取行为类型
 * @param intger $type 类型
 * @param bool $all 是否返回全部类型
 * @author huajie <banhuajie@163.com>
 */
function get_action_type($type, $all = false) {
    $list = array(
        1 => '系统',
        2 => '用户',
    );
    if ($all) {
        return $list;
    }
    return $list[$type];
}

/**
 * 导出excel.xls文件
 * @param string $fileName 文件名
 * @param array $arrHead   表头
 * @param array $data      表值
 */
function exportExcel($fileName, $arrHead, $data) {

    import("Vendor.PHPExcel");
//    import("Org.Util.PHPExcel.Writer.Excel5");
//    import("Org.Util.PHPExcel.IOFactory.php");
//    vendor("PHPExcel");
//    vendor("PHPExcel.Writer.Excel5");
//    vendor("PHPExcel.IOFactory.php");
    //对数据进行检验
    if (empty($data) || !is_array($data)) {
        die("导出excel数据不存在");
    }
    //检查文件名
    if (empty($fileName)) {
        exit;
    }

    $date = date("Y_m_d", time());
    $fileName .= "_{$date}.xls";

    $objPHPExcel = new \PHPExcel();

    $objProps = $objPHPExcel->getProperties();

    //设置表头
    $key = ord("A");
    foreach ($arrHead as $v) {
        $colum = chr($key);
        $objPHPExcel->setActiveSheetIndex(0)->setCellValue($colum . '1', $v);
        $key += 1;
    }

    $column = 2;
    $objActSheet = $objPHPExcel->getActiveSheet();
    foreach ($data as $key => $rows) { //行写入
        $span = ord("A");
        foreach ($rows as $keyName => $value) {// 列写入
            $j = chr($span);
            $objActSheet->setCellValue($j . $column, $value);
            $span++;
        }
        $column++;
    }

    $fileName = iconv("utf-8", "gb2312", $fileName);
    //重命名表
    // $objPHPExcel->getActiveSheet()->setTitle('test');
    //打开这是第一个表
    $objPHPExcel->setActiveSheetIndex(0);
    header('Content-Type: application/vnd.ms-excel');
    header("Content-Disposition: attachment;filename=\"$fileName\"");
    header('Cache-Control: max-age=0');

    $objWriter = \PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel5');
    $objWriter->save('php://output');
    exit;
}

function ExcelDuihuanCard($Obj) {

    /* 引入phpexcel核心类文件 */

    import("Vendor.PHPExcel");

    /* 实例化excel类 */

    $excel = new \PHPExcel();


    /* 实例化excel图片处理类 */

    $objDrawing = new \PHPExcel_Worksheet_Drawing();



    /* 设置文本对齐方式 */

    $excel->getDefaultStyle()->getAlignment()->setHorizontal(\PHPExcel_Style_Alignment::HORIZONTAL_CENTER);

    $excel->getDefaultStyle()->getAlignment()->setVertical(\PHPExcel_Style_Alignment::VERTICAL_CENTER);

    $objActSheet = $excel->getActiveSheet();

    $letter = array('A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N');

    /* 设置表头数据 */
    $tableheader = array('编号', '名称', '卡号', '密码', '可变现金额', '状态', '生成时间', '有效期', '卡号条形码');


    /*    填充表格表头 */

    for ($i = 0; $i < count($tableheader); $i++) {

        $excel->getActiveSheet()->setCellValue("$letter[$i]1", "$tableheader[$i]");
        /* 设置font */
        $excel->getActiveSheet()->getStyle("$letter[$i]1")->getFont()->setName(iconv('gbk', 'utf-8', '宋体'));
        $excel->getActiveSheet()->getStyle("$letter[$i]1")->getFont()->setSize(16);
        $excel->getActiveSheet()->getStyle("$letter[$i]1")->getFont()->setBold(true);
        /* 设置下划线 */
        //$excel->getActiveSheet()->getStyle("$letter[$i]1")->getFont()->setUnderline(PHPExcel_Style_Font::UNDERLINE_SINGLE);
        /* 设置字体颜色 */
        //$excel->getActiveSheet()->getStyle("$letter[$i]1")->getFont()->getColor()->setARGB(PHPExcel_Style_Color::COLOR_WHITE);
        //$excel->getActiveSheet()->getStyle("$letter[$i]1")->getFont()->getColor()->setARGB(PHPExcel_Style_Color::COLOR_WHITE);
        /* 设置表格宽度 */
        $objActSheet->getColumnDimension("$letter[$i]")->setWidth(20);
        $objActSheet->getColumnDimension("$letter[2]")->setWidth(30);
        $objActSheet->getColumnDimension("$letter[5]")->setWidth(10);
    }

    $startdate = !empty($_POST['startdate']) ? $_POST['startdate'] : date('Y-m-d', time());

    /* 设置表格数据 */

    if (!empty($Obj)) {
        foreach ($Obj as $k => $v) {
//            $img = '/Uploads/Qcode/' . trim($v['card_number']) . '.png';
            list($Oldrwidth, $Oldheight) = getimagesize($v['qcode']);
            if ($Oldrwidth > 126 && $Oldheight > 102) {
                $Obj[$k]['photos'] = $v['qcode'];
            } else {
                $Obj[$k]['photos'] = $v['qcode'];
            }
            if ($v['status'] == 0) {
                $Obj[$k]['status'] = '正常';
            } else {
                $Obj[$k]['status'] = '已消费';
            }
            unset($Obj[$k]['photo']);
            unset($Obj[$k]['photo_s']);
        }
    }


    /* 向每行单元格插入数据 */

    for ($i = 0; $i < count($Obj); $i++) {



        $j = $i + 2;

        /* 设置表格高度 */

        $excel->getActiveSheet()->getRowDimension($j)->setRowHeight(35);
        $excel->getActiveSheet()->getStyle($j)->getFont()->setSize(12);
        /* 设置表格格式 */
        $excel->getActiveSheet()->getStyle("$letter[2]$j")->getNumberFormat()->setFormatCode(PHPExcel_Style_NumberFormat::FORMAT_NUMBER);
        for ($row = 0; $row < count($Obj[$i]); $row++) {
            if ($row == (count($Obj[$i]) - 1 )) {

                /* 实例化excel图片处理类 */

                $objDrawing = new \PHPExcel_Worksheet_Drawing();
//                if (!empty($Obj[$i]['photos'])) {
//                    $photo = substr($Obj[$i]['photos'], 7);
//                    $photoAry = explode('/', $photo);
//
//                    if (in_array('uploadfiles', $photoAry)) {
//                        unset($photoAry[0]);
//                        $photos = implode('/', $photoAry);
//                        //var_dump($photos);exit;
//                        /* 设置图片路径 切记：只能是本地图片 */
//                        $objDrawing->setPath('');
//                    }
//                } else {
//
//                    $objDrawing->setPath($photos, false);
//                }


                $objDrawing->setPath('./Uploads/Barcode/' . trim($Obj[$i]['card_number']) . '.png');
                /* 设置图片高度 */
                $objDrawing->setWidth(120);
                $objDrawing->setHeight(40);

                /* 设置图片要插入的单元格 */

                $objDrawing->setCoordinates("I" . ($i + 2));


                /* 设置图片所在单元格的格式 */

                $objDrawing->setOffsetX(2);
                $objDrawing->setOffsetY(5);
                $objDrawing->setRotation(20);

                $objDrawing->getShadow()->setVisible(true);

                $objDrawing->getShadow()->setDirection(50);

                $objDrawing->setWorksheet($excel->getActiveSheet());

                continue;
            }

//     field('c.card_id,c.card_name, CONCAT(c.card_number," ") as card_number ,CONCAT(c.card_password," ") as card_password,c.card_price,c.status,c.create_time,c.end_time,c.goods_id')
// $objDrawing->setPath($Obj[$i]['qcode']);
// dump($objDrawing);die;
            $excel->getActiveSheet()->setCellValue("$letter[0]$j", $Obj[$i]['card_id']);
            $excel->getActiveSheet()->setCellValue("$letter[1]$j", $Obj[$i]['card_name']);
            $excel->getActiveSheet()->setCellValue("$letter[2]$j", $Obj[$i]['card_number']);
            $excel->getActiveSheet()->setCellValue("$letter[3]$j", $Obj[$i]['card_password']);
            $excel->getActiveSheet()->setCellValue("$letter[4]$j", $Obj[$i]['card_price']);
            $excel->getActiveSheet()->setCellValue("$letter[5]$j", $Obj[$i]['status']);
            $excel->getActiveSheet()->setCellValue("$letter[6]$j", $Obj[$i]['create_time']);
            $excel->getActiveSheet()->setCellValue("$letter[7]$j", $Obj[$i]['end_time']);
//            $excel->getActiveSheet()->setCellValue("$letter[8]$j", '');
//            $excel->getActiveSheet()->setCellValue("$letter[9]$j", $Obj[$i]['qcode']);
        }
    }
    $date = "提货卡-" . $startdate;

    /* 实例化excel输入类并完成输出excel文件 */

    $write = new \PHPExcel_Writer_Excel5($excel);
    //var_dump($write);exit;

    header("Pragma: public");

    header("Expires: 0");

    header("Cache-Control:must-revalidate, post-check=0, pre-check=0");

    header("Content-Type:application/force-download");

    header("Content-Type:application/vnd.ms-execl");

    header("Content-Type:application/octet-stream");

    header("Content-Type:application/download");
    header("Content-Disposition:attachment;filename=$date.xls");

    header("Content-Transfer-Encoding:binary");

    $write->save('php://output');


    exit;


    //var_dump($row);exit;
}

function ExcelXiaofeiCard($Obj) {

    /* 引入phpexcel核心类文件 */

    import("Vendor.PHPExcel");

    /* 实例化excel类 */

    $excel = new \PHPExcel();


    /* 实例化excel图片处理类 */

    $objDrawing = new \PHPExcel_Worksheet_Drawing();



    /* 设置文本对齐方式 */

    $excel->getDefaultStyle()->getAlignment()->setHorizontal(\PHPExcel_Style_Alignment::HORIZONTAL_CENTER);

    $excel->getDefaultStyle()->getAlignment()->setVertical(\PHPExcel_Style_Alignment::VERTICAL_CENTER);

    $objActSheet = $excel->getActiveSheet();

    $letter = array('A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N');

    /* 设置表头数据 */
    $tableheader = array('编号', '名称', '卡号', '密码', '金额', '状态', '生成时间', '有效期', '卡号条形码');


    /*    填充表格表头 */

    for ($i = 0; $i < count($tableheader); $i++) {

        $excel->getActiveSheet()->setCellValue("$letter[$i]1", "$tableheader[$i]");
        /* 设置font */
        $excel->getActiveSheet()->getStyle("$letter[$i]1")->getFont()->setName(iconv('gbk', 'utf-8', '宋体'));
        $excel->getActiveSheet()->getStyle("$letter[$i]1")->getFont()->setSize(16);
        $excel->getActiveSheet()->getStyle("$letter[$i]1")->getFont()->setBold(true);
        /* 设置下划线 */
        //$excel->getActiveSheet()->getStyle("$letter[$i]1")->getFont()->setUnderline(PHPExcel_Style_Font::UNDERLINE_SINGLE);
        /* 设置字体颜色 */
        //$excel->getActiveSheet()->getStyle("$letter[$i]1")->getFont()->getColor()->setARGB(PHPExcel_Style_Color::COLOR_WHITE);
        //$excel->getActiveSheet()->getStyle("$letter[$i]1")->getFont()->getColor()->setARGB(PHPExcel_Style_Color::COLOR_WHITE);
        /* 设置表格宽度 */
        $objActSheet->getColumnDimension("$letter[$i]")->setWidth(20);
        $objActSheet->getColumnDimension("$letter[2]")->setWidth(30);
        $objActSheet->getColumnDimension("$letter[5]")->setWidth(10);
    }

    $startdate = !empty($_POST['startdate']) ? $_POST['startdate'] : date('Y-m-d', time());

    /* 设置表格数据 */

    if (!empty($Obj)) {
        foreach ($Obj as $k => $v) {
//            $img = '/Uploads/Qcode/' . trim($v['card_number']) . '.png';
            list($Oldrwidth, $Oldheight) = getimagesize($v['qcode']);
            if ($Oldrwidth > 126 && $Oldheight > 102) {
                $Obj[$k]['photos'] = $v['qcode'];
            } else {
                $Obj[$k]['photos'] = $v['qcode'];
            }
            if ($v['status'] == 0) {
                $Obj[$k]['status'] = '正常';
            } else {
                $Obj[$k]['status'] = '已消费';
            }
            unset($Obj[$k]['photo']);
            unset($Obj[$k]['photo_s']);
        }
    }


    /* 向每行单元格插入数据 */

    for ($i = 0; $i < count($Obj); $i++) {



        $j = $i + 2;

        /* 设置表格高度 */

        $excel->getActiveSheet()->getRowDimension($j)->setRowHeight(35);
        $excel->getActiveSheet()->getStyle($j)->getFont()->setSize(12);
        /* 设置表格格式 */
        $excel->getActiveSheet()->getStyle("$letter[2]$j")->getNumberFormat()->setFormatCode(PHPExcel_Style_NumberFormat::FORMAT_NUMBER);
        for ($row = 0; $row < count($Obj[$i]); $row++) {
            if ($row == (count($Obj[$i]) - 1 )) {

                /* 实例化excel图片处理类 */

                $objDrawing = new \PHPExcel_Worksheet_Drawing();
//                if (!empty($Obj[$i]['photos'])) {
//                    $photo = substr($Obj[$i]['photos'], 7);
//                    $photoAry = explode('/', $photo);
//
//                    if (in_array('uploadfiles', $photoAry)) {
//                        unset($photoAry[0]);
//                        $photos = implode('/', $photoAry);
//                        //var_dump($photos);exit;
//                        /* 设置图片路径 切记：只能是本地图片 */
//                        $objDrawing->setPath('');
//                    }
//                } else {
//
//                    $objDrawing->setPath($photos, false);
//                }


                $objDrawing->setPath('./Uploads/Barcode/' . trim($Obj[$i]['card_number']) . '.png');
                /* 设置图片高度 */
                $objDrawing->setWidth(120);
                $objDrawing->setHeight(40);

                /* 设置图片要插入的单元格 */

                $objDrawing->setCoordinates("I" . ($i + 2));


                /* 设置图片所在单元格的格式 */

                $objDrawing->setOffsetX(2);
                $objDrawing->setOffsetY(5);
                $objDrawing->setRotation(20);

                $objDrawing->getShadow()->setVisible(true);

                $objDrawing->getShadow()->setDirection(50);

                $objDrawing->setWorksheet($excel->getActiveSheet());

                continue;
            }

//     field('c.card_id,c.card_name, CONCAT(c.card_number," ") as card_number ,CONCAT(c.card_password," ") as card_password,c.card_price,c.status,c.create_time,c.end_time,c.goods_id')
// $objDrawing->setPath($Obj[$i]['qcode']);
// dump($objDrawing);die;
            $excel->getActiveSheet()->setCellValue("$letter[0]$j", $Obj[$i]['card_id']);
            $excel->getActiveSheet()->setCellValue("$letter[1]$j", $Obj[$i]['card_name']);
            $excel->getActiveSheet()->setCellValue("$letter[2]$j", $Obj[$i]['card_number']);
            $excel->getActiveSheet()->setCellValue("$letter[3]$j", $Obj[$i]['card_password']);
            $excel->getActiveSheet()->setCellValue("$letter[4]$j", $Obj[$i]['card_price']);
            $excel->getActiveSheet()->setCellValue("$letter[5]$j", $Obj[$i]['status']);
            $excel->getActiveSheet()->setCellValue("$letter[6]$j", $Obj[$i]['create_time']);
            $excel->getActiveSheet()->setCellValue("$letter[7]$j", $Obj[$i]['end_time']);
//            $excel->getActiveSheet()->setCellValue("$letter[8]$j", $Obj[$i]['goods_id']);
//            $excel->getActiveSheet()->setCellValue("$letter[9]$j", $Obj[$i]['qcode']);
        }
    }
    $date = "购物卡-" . $startdate;

    /* 实例化excel输入类并完成输出excel文件 */

    $write = new \PHPExcel_Writer_Excel5($excel);
    //var_dump($write);exit;

    header("Pragma: public");

    header("Expires: 0");

    header("Cache-Control:must-revalidate, post-check=0, pre-check=0");

    header("Content-Type:application/force-download");

    header("Content-Type:application/vnd.ms-execl");

    header("Content-Type:application/octet-stream");

    header("Content-Type:application/download");
    header("Content-Disposition:attachment;filename=$date.xls");

    header("Content-Transfer-Encoding:binary");

    $write->save('php://output');


    exit;


    //var_dump($row);exit;
}

function combinationList($d) {
    //计算每一个数组的长度
    $len = 1;
    $arrLen = count($d); //需要排列数组有多少个
    $recIndex = null; //记录当前该取的位置
    //foreach 计数 
    $count_3 = 0;
    foreach ($d as $key => $value) {
        $lenRec[$count_3] = count($value);
        $len = $lenRec[$count_3] * $len;
        $recIndex[] = 0; //第一次全部取第0个
        $count_3++;
    }
    //算出% 的值
    $count = 1;
    foreach ($lenRec as $key => $value) {
        $moduloVal = 1;

        if ($arrLen == $count) {
            $modulo[] = count($d[$arrLen - 1]); //等于最后一个的长度
        } else {
            $count_1 = 1;
            foreach ($lenRec as $index => $item) {
                $count_1 > $count && $moduloVal = $moduloVal * $item;
                $count_1 ++;
            }
            $modulo[] = $moduloVal;
        }
        $count ++; //为了防止$d key是有值的 不是自然序列 需要计数
    }
    $i = 1;

    while ($i <= $len) {
        $count_2 = 0; // 取模
        $temp = '';
        foreach ($d as $value) {
            $arr_data[$i][] = $value[$recIndex[$count_2] % $lenRec[$count_2]];
            $count_2 ++;
        }
        foreach ($modulo as $key => $value) {
            if ($i % $value == 0 && $key < $arrLen - 1) {
                $recIndex[$key] = $recIndex[$key] + 1;
            }
            if ($key == $arrLen - 1) {
                if ($i % $value == 0) {
                    $recIndex[$key] = 0;
                } else {
                    $recIndex[$key] = $recIndex[$key] + 1;
                }
            }
        }
        $i ++;
    }

//    foreach ($arr_data as $key => $val) {
//        $arr_result[] = implode(',', $val);
//    }
    return $arr_data;
}

function createBarcode($card_number) {
    import("Vendor.Barcode.class.BCGColor", '', '.php');
    import("Vendor.Barcode.class.BCGDrawing", '', '.php');
    import("Vendor.Barcode.class.BCGcode128", '', '.php');

    $colorFront = new BCGColor(0, 0, 0);
    $colorBack = new BCGColor(255, 255, 255);

// Barcode Part
    $code = new BCGcode128();
    $code->setScale(2);
    $code->setColor($colorFront, $colorBack);
    $code->parse($card_number);

// Drawing Part
    $drawing = new BCGDrawing('', $colorBack);
    $drawing->setBarcode($code);
    $drawing->draw();

    header('Content-Type: image/png');

    $drawing->setFilename('./Uploads/Barcode/' . $card_number . '.png');
    $drawing->finish(BCGDrawing::IMG_FORMAT_PNG);

}

//刷卡支付返回
function returnMicroPay($auth_code, $total_fee, $body = "国知商城商品购买") {
    vendor('WxPay.lib.WxPay', '', '.Api.php');
    vendor('WxPay.WxPay', '', '.MicroPay.php');

//    $auth_code = $_REQUEST["auth_code"];
    $input = new \WxPayMicroPay();
    $input->SetAuth_code($auth_code);
    $input->SetBody($body);
    $input->SetTotal_fee($total_fee);
    $input->SetOut_trade_no(\WxPayConfig::MCHID . date("YmdHis"));

    $microPay = new \MicroPay();
    return $microPay->pay($input);
}

